package com.genuine.jubao;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.Charset;

import com.genuine.hyjj.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class JbpostActivity extends Activity {
	private static final String[] STATUS_STR = { "密码错误", "已被查询", "没有此产品" };

	private String end = "\r\n";
	private String twoHyphens = "--";
	private String boundary = "----HyjjFromBoundaryHhjk9298jh21381283821HJKJ";

	private String code = "0";
	private EditText myedittext_phonenum;
	private EditText myedittext_msg;
	private Spinner myspinner_status;
	private Button mybtn_camera;
	private Button mybtn_post;
	private ImageView mypic;
	private ProgressDialog pDialog;

	private Bitmap bmp = null;
	private int status = 1;
	private ArrayAdapter<String> adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jubao);
		mybtn_post = (Button) findViewById(R.id.postbtn);
		mybtn_camera = (Button) findViewById(R.id.camerabtn);
		Intent intent = getIntent();
		code = intent.getStringExtra("code");

		mybtn_camera.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// 启动照相机拍�?
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(i, Activity.DEFAULT_KEYS_DIALER);
			}
		});

		mybtn_post.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				new PostTask().execute(null);
			}
		});

		myedittext_phonenum = (EditText) findViewById(R.id.phonenum);
		myedittext_msg = (EditText) findViewById(R.id.jubao_msg);
		myspinner_status = (Spinner) findViewById(R.id.status);
		mypic = (ImageView) findViewById(R.id.jubao_pic);

		// 将可选内容与ArrayAdapter连接起来
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, STATUS_STR);
		// 设置下拉列表的风�?
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter 添加到spinner�?
		myspinner_status.setAdapter(adapter);

		myspinner_status
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						status=0;
						status=arg2+1;
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						status = 0;
					}
				});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			super.onActivityResult(requestCode, resultCode, data);
			if (data != null) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					bmp = (Bitmap) extras.get("data");
					mypic.setImageBitmap(bmp);
					mypic.setVisibility(View.VISIBLE);
				}
			}
			break;
		default:
			break;
		}

	}

	/* 上传文件至Server的方�? */
	private boolean uploadFile(String actionUrl, String newName, Bitmap bitmap) {
		URL url = null;
		HttpURLConnection con = null;
		DataOutputStream dos = null;
		InputStream is = null;

		try {
			url = new URL(actionUrl);
			con = (HttpURLConnection) url.openConnection();

			// 写入POST请求头部信息
			writeFromHead(con);

			dos = new DataOutputStream(con.getOutputStream());

			// 设置默认�?
			if (myedittext_phonenum.getText() == null)
				myedittext_phonenum.setText("0");
			if (myedittext_msg.getText() == null)
				myedittext_msg.setText("0");

			// 字段表单
			Log.d("demo", "填入表单字段1");
			autoFromField(dos, "barcode", code.toString());
			Log.d("demo", "填入表单字段2");
			autoFromField(dos, "phoneno", myedittext_phonenum.getText()
					.toString());
			Log.d("demo", "填入表单字段3");
			autoFromField(dos, "msg", new String(myedittext_msg.getText()
					.toString().getBytes(), Charset.forName("utf-8")));
			Log.d("demo", "填入表单字段4");
			autoFromField(dos, "status", Integer.toString(status));
			Log.d("demo", "填入表单字段5");
			SharedPreferences sharedPreferences = getSharedPreferences("hyjj",
					Context.MODE_PRIVATE);
			String cuanhao = sharedPreferences.getString("deviceId", "默认");
			autoFromField(dos, "imei", cuanhao);
			Log.d("demo", "填入表单文件");
			if (bitmap != null) {
				autoFromFile(dos, "pic", bitmap, newName);
			}

			// 字段表单end
			// 刷新缓冲�? Log.d("demo", "刷新缓冲�?);
			dos.flush();

			Log.d("demo", con.getResponseCode() + "");
			Log.d("demo", con.getRequestMethod());

			Log.d("demo", "取得服务器返回的数据");
			is = con.getInputStream();
			// 取得Response内容
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			// 关闭DataOutputStream
			// 关闭InputStream
			dos.close();
			is.close();

			Log.d("demo", "服务器返�? " + b);
			if (b.toString().equals("1"))
				return true;
			else
				return false;
		} catch (ProtocolException e) {
			Log.d("demo",
					"ProtocolException-----------------------------------------------");
			e.printStackTrace();
			Log.d("demo",
					"ProtocolException-----------------------------------------------");
			return false;
		} catch (IOException e) {
			Log.d("demo",
					"IOException-----------------------------------------------");
			e.printStackTrace();
			Log.d("demo",
					"IOException-----------------------------------------------");
			return false;
		} finally {
			con.disconnect();
		}
	}

	private void autoFromFile(DataOutputStream ds, String key, Bitmap bitmap,
			String newFileName) throws IOException {
		// 设置DataOutputStream
		ds.writeBytes(twoHyphens + boundary + end);
		ds.writeBytes("Content-Disposition: form-data; " + "name=\"" + key
				+ "\";filename=\"" + newFileName + "\"" + end);
		ds.writeBytes(end);

		// 取得图片字节�?
		Log.d("demo", "取得压缩后的图片字节");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] bitmap_data = baos.toByteArray();
		Log.d("demo", "已经取得压缩后的图片字节");

		// 设置每次写入1024bytes
		int bitmapSize = bitmap_data.length;
		Log.d("demo", "上传压缩后的图片字节�?- " + bitmapSize);
		int bufferSize = 1024;
		byte[] buffer = new byte[bufferSize];
		int i = 0;
		// 从文件读取数据至缓冲�?
		while (bitmapSize > 0) {
			// 将资料写入DataOutputStream�?
			if (bitmapSize >= bufferSize) {
				System.arraycopy(bitmap_data, i * bufferSize, buffer, 0,
						bufferSize);
				ds.write(buffer, 0, bufferSize);
				i++;
				Log.d("demo", "上传 - " + bufferSize);
				bitmapSize -= bufferSize;
				Log.d("demo", "剩余 - " + bitmapSize);
			} else {
				buffer = new byte[bitmapSize];
				System.arraycopy(bitmap_data, i * bufferSize, buffer, 0,
						bitmapSize);
				ds.write(buffer, 0, bitmapSize);
				Log.d("demo", "上传 - " + bitmapSize);
				bitmapSize -= bitmapSize;
				Log.d("demo", "剩余 - " + bitmapSize);
			}
		}
		baos.close();
		Log.d("demo", "已经上传压缩后的图片字节");

		ds.writeBytes(end);
		ds.writeBytes(twoHyphens + boundary + end);
		// close streams
	}

	private void autoFromField(DataOutputStream ds, String key, String value)
			throws IOException {
		// 加入传�?的参数头部信息
		ds.writeBytes(twoHyphens + boundary + end);
		ds.writeBytes("Content-Disposition: form-data; " + "name=\"" + key
				+ "\"" + end);

		// 加入传�?的参数实际信息
		ds.writeBytes(end);
		ds.write(value.getBytes());
		ds.writeBytes(end);
		ds.writeBytes(twoHyphens + boundary + end);
	}

	private void writeFromHead(HttpURLConnection con) throws ProtocolException {
		/* 允许Input、Output，不使用Cache */
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		/* 设置传�?的method=POST */
		con.setRequestMethod("POST");
		/* setRequestProperty */
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty("Content-Type", "multipart/form-data;boundary="
				+ boundary);
	}

	class PostTask extends AsyncTask {

		boolean i = false;

		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.dismiss();
			if (i)
				Toast.makeText(JbpostActivity.this, "上传成功", Toast.LENGTH_SHORT)
						.show();
			else
				Toast.makeText(JbpostActivity.this, "上传失败", Toast.LENGTH_LONG)
						.show();

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pDialog = pDialog.show(JbpostActivity.this, "举报", "正在提交...");
			pDialog.show();
		}

		@Override
		protected Object doInBackground(Object... arg0) {
			// TODO Auto-generated method stub
			i = uploadFile(
					"http://www.ypdm.com/Handler/Consumer/ConsumerInform.ashx",
					"test.gif", bmp);

			return null;
		}

	}
}